<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<el-row :gutter="20">
					<!-- 只读字段区 -->
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name" :rules="[{ required: true, message: '名称为必填项', trigger: 'blur' }]">
							<template #label>
								<WtmLabelTooltip label="名称" tooltip="物料名称" />
							</template>
							<el-input v-model="stateData.vmModel.Entity.Name" disabled class="width100"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_Code_FormItem" prop="Entity.Code">
							<template #label>
								<WtmLabelTooltip label="编码" tooltip="物料唯一编码，用于系统内标识物料" />
							</template>
							<el-input v-model="stateData.vmModel.Entity.Code" disabled class="width100"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_ErpId_FormItem" prop="Entity.ErpId">
							<template #label>
								<WtmLabelTooltip label="金蝶ERP编号" tooltip="与外部ERP系统同步时使用的编号" />
							</template>
							<el-input v-model="stateData.vmModel.Entity.ErpId" disabled class="width100"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_MaterialId_FormItem" prop="Entity.MaterialId">
							<template #label>
								<WtmLabelTooltip label="物料" tooltip="所属物料信息" />
							</template>
							<el-input v-model="stateData.vmModel.MaterialName" disabled class="width100"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_BarCode_FormItem" prop="Entity.BarCode">
							<template #label>
								<WtmLabelTooltip label="条形码" tooltip="物料条形码，用于扫码识别" />
							</template>
							<el-input v-model="stateData.vmModel.Entity.BarCode" disabled class="width100"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_TaxPrice_FormItem"
							prop="Entity.TaxPrice"
							:rules="[{ required: true, message: '含税单价为必填项', trigger: 'blur' }]"
						>
							<template #label>
								<WtmLabelTooltip label="含税单价" tooltip="最近一次采购或销售的含税单价" />
							</template>
							<el-input-number v-model="stateData.vmModel.Entity.TaxPrice" disabled class="width100"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_Price_FormItem" prop="Entity.Price" :rules="[{ required: true, message: '单价为必填项', trigger: 'blur' }]">
							<template #label>
								<WtmLabelTooltip label="单价" tooltip="最近一次采购或销售的不含税单价" />
							</template>
							<el-input-number v-model="stateData.vmModel.Entity.Price" disabled class="width100"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_LastInStockTime_FormItem" prop="Entity.LastInStockTime">
							<template #label>
								<WtmLabelTooltip label="最近入库时间" tooltip="物料最近一次入库的时间" />
							</template>
							<el-date-picker v-model="stateData.vmModel.Entity.LastInStockTime" disabled class="width100"></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_State_FormItem" prop="Entity.State" :rules="[{ required: true, message: '状态为必填项', trigger: 'blur' }]">
							<template #label>
								<WtmLabelTooltip label="状态" tooltip="物料当前状态（启用/禁用等）" />
							</template>
							<el-select v-model="stateData.vmModel.Entity.State" disabled class="width100">
								<el-option key="启用" value="启用" label="启用"></el-option>
								<el-option key="禁用" value="禁用" label="禁用"></el-option>
								<el-option key="废弃" value="废弃" label="废弃"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_UnitId_FormItem" prop="Entity.UnitId">
							<template #label>
								<WtmLabelTooltip label="计量单位" tooltip="物料计量单位信息" />
							</template>
							<el-select v-model="stateData.vmModel.Entity.UnitId" disabled class="width100">
								<el-option v-for="item in stateData.AllSysMeasureUnits" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="24" class="mb20">
						<el-form-item ref="Entity_Description_FormItem" prop="Entity.Description">
							<template #label>
								<WtmLabelTooltip label="详情" tooltip="物料详细描述信息" />
							</template>
							<el-input type="textarea" :rows="3" v-model="stateData.vmModel.Entity.Description" disabled></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="24" class="mb20">
						<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
							<template #label>
								<WtmLabelTooltip label="备注" tooltip="计量单位组的备注信息" />
							</template>
							<el-input type="textarea" :rows="3" v-model="stateData.vmModel.Entity.Remark" disabled></el-input>
						</el-form-item>
					</el-col>

					<!-- 属性列表区 -->
					<el-col :xs="24" :lg="24" class="mb20">
						<el-form-item ref="SelectedAttributesIds_FormItem" prop="SelectedAttributesIds">
							<template #label>
								<WtmLabelTooltip label="属性列表" tooltip="SKU属性列表" />
							</template>
							<WtmSkuAttributeSelector
								:material-id="stateData.vmModel.Entity.MaterialId"
								:selected-ids="stateData.vmModel"
								:is-purchase-scenario="true"
								:disabled="true"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.edit;false">
import { reactive, ref, getCurrentInstance, onMounted, nextTick, ComponentInternalInstance } from 'vue';
import { SysMaterialSkuApi as api } from '/@/views/supplychain/sysmaterialsku/api';
import { SysMaterialAttributeApi as attributeApi } from '/@/views/supplychain/sysmaterialattribute/api';
import { SysMaterialApi as materialApi } from '/@/views/supplychain/sysmaterial/api';
import { SysMeasureUnitApi as measureUnitApi } from '/@/views/supplychain/sysmeasureunit/api';
import other from '/@/utils/other';
import { ISysMaterialSkuVm } from '/@/views/supplychain/sysmaterialsku/api/interface';
import { ISysSelectType, IViewModel } from '/@/types/common';

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);
const stateData = reactive<IViewModel<ISysMaterialSkuVm>>({
	vmModel: {
		Entity: {
			ID: null,
			Name: null,
			Code: null,
			ErpId: null,
			Description: null,
			State: '启用',
			BarCode: null,
			TaxPrice: null,
			Price: null,
			LastInStockTime: null,
			UnitId: null,
			MaterialId: null,
			Remark: null,
			Attributes: null,
		},
		SelectedAttributesIds: [],
		MaterialName: null,
	},
	AllSysMeasureUnits: [] as ISysSelectType[],
	AllSysMaterials: [] as ISysSelectType[],
	AllSysMaterialAttributeValues: [] as ISysSelectType[],
});

// 关闭
const onClose = () => {
	closeDialog();
};

const closeDialog = () => {
	emit('closeDialog');
};

// 根据物料分组ID加载计量单位
const loadMeasureUnitsByGroupId = async (measureUnitGroupId: string | null) => {
	if (!measureUnitGroupId) {
		stateData.AllSysMeasureUnits = [];
		return;
	}

	try {
		const response: any = await measureUnitApi().search({
			MeasureUnitGroupId: measureUnitGroupId,
		});

		const dataList = response.data?.Data || response.Data || response.data || [];

		if (Array.isArray(dataList)) {
			stateData.AllSysMeasureUnits = dataList.map((unit: any) => ({
				Value: unit.ID,
				Text: unit.Name,
			}));
		} else {
			stateData.AllSysMeasureUnits = [];
		}
	} catch (error) {
		console.error('加载计量单位失败:', error);
		stateData.AllSysMeasureUnits = [];
	}
};

// 加载数据
const loadData = async () => {
	await Promise.allSettled([
		api()
			.get(stateData.vmModel.Entity.ID ?? '')
			.then(async (x) => {
				other.setValue(stateData.vmModel, x);
				// 加载完数据后，根据物料ID加载对应的属性值
				if (stateData.vmModel.Entity.MaterialId) {
					await loadAttributeValues(stateData.vmModel.Entity.MaterialId);
				}
				// 根据物料ID查询物料信息，获取计量单位组ID
				if (stateData.vmModel.Entity.MaterialId) {
					await loadMeasureUnitsByMaterialId(stateData.vmModel.Entity.MaterialId);
				}
			}),
	]);
};

// 根据物料ID加载计量单位
const loadMeasureUnitsByMaterialId = async (materialId: string) => {
	try {
		const materialResponse: any = await materialApi().get(materialId);
		const measureUnitGroupId =
			materialResponse?.data?.Entity?.Unit?.MeasureUnitGroupId ||
			materialResponse?.Entity?.Unit?.MeasureUnitGroupId ||
			materialResponse?.data?.Unit?.MeasureUnitGroupId;

		if (measureUnitGroupId) {
			await loadMeasureUnitsByGroupId(measureUnitGroupId);
		} else {
			stateData.AllSysMeasureUnits = [];
		}
	} catch (error) {
		console.error('加载物料信息失败:', error);
		stateData.AllSysMeasureUnits = [];
	}
};

// 根据物料ID加载属性值
const loadAttributeValues = async (materialId: string) => {
	try {
		const attributeResponse: any = await attributeApi().search({
			MaterialId: materialId,
		});

		const attributeValues: any[] = [];
		if (attributeResponse.Data && Array.isArray(attributeResponse.Data)) {
			attributeResponse.Data.forEach((attr: any) => {
				if (attr.Values && Array.isArray(attr.Values)) {
					attr.Values.forEach((value: any) => {
						attributeValues.push({
							Value: value.ID,
							Text: `${attr.Name}: ${value.Value}`,
						});
					});
				}
			});
		}

		stateData.AllSysMaterialAttributeValues = attributeValues;
	} catch (error) {
		console.error('加载物料属性值失败:', error);
		stateData.AllSysMaterialAttributeValues = [];
	}
};

// 设置头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: '关闭',
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};

// 页面加载时
onMounted(async () => {
	loading.value = true;

	// 初始化ID
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	}

	try {
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});
</script>
